package cli;

import statistic.StudentGPAList;

import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Scanner;

public class StudentList implements CommandLineInterface.Handler {

    private StudentGPAList.Order inputOrder(Scanner in, PrintWriter out) {
        out.println("按学号排序，还是按成绩排序？");
        return in.next().contains("学号") ? StudentGPAList.Order.ID : StudentGPAList.Order.GPA;
    }

    private static void outputPage(PrintWriter out, StudentGPAList list) {
        if (list == null)
            return;
        String[] header = {"序号", "学号", "姓名", "平均成绩"};
        String[][] table = new String[list.students.size()][header.length];
        for (int i = 0; i < list.students.size(); ++i) {
            table[i][0] = Integer.toString(  list.pageIdx * list.pageSize + i + 1);
            table[i][1] = list.students.get(i).getId();
            table[i][2] = list.students.get(i).getName();
            table[i][3] = String.format("%.1f", list.GPA.get(i));
        }
        out.println(new TableLayout(header, table));
        out.printf("第%d页\t共%d页\t请输入页码或退出：\n", 1 + list.pageIdx, list.pageTotal);
    }

    @Override
    public void handle(Scanner in, PrintWriter out) {
        try {
            StudentGPAList.Order order = inputOrder(in, out);
            StudentGPAList list = new StudentGPAList(StudentGPAList.Aggregate.AVERAGE, order, 0, 30);
            outputPage(out, list);
            while (true) {
                try {
                    int idx = Integer.parseUnsignedInt(in.next());
                    if (idx < 1 || list.pageTotal < idx)
                        break;
                    list = new StudentGPAList(StudentGPAList.Aggregate.AVERAGE, order, idx - 1, list.pageSize);
                    outputPage(out, list);
                } catch (NumberFormatException e) {
                    break;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
